<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>12-光线投射2</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html,
    body {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <script type="module">
    // 引入three.js
      import * as THREE from "three";
      import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

      //创建场景
      const scene = new THREE.Scene();

      //创建相机
      const camera = new THREE.PerspectiveCamera(
        45,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );
      //设置相机位置
      camera.position.set(0, 0, 50); //统一设置
      //设置相机朝向点位
      camera.lookAt(0, 0, 0);

      //创建渲染器
      const renderer = new THREE.WebGLRenderer({
        antialias: true, //减少边缘齿轮
      });
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.shadowMap.enabled = true; //开启阴影投射
      document.body.appendChild(renderer.domElement);

      //创建结构-几何体
      const sphere1 = new THREE.Mesh(
        new THREE.SphereGeometry(1, 32, 32),
        new THREE.MeshBasicMaterial({ color: 0xffff32 })
      );
      sphere1.position.x = -4;

      const sphere2 = new THREE.Mesh(
        new THREE.SphereGeometry(1, 32, 32),
        new THREE.MeshBasicMaterial({ color: 0xffff32 })
      );
      sphere2.position.y = 4;

      const sphere3 = new THREE.Mesh(
        new THREE.SphereGeometry(1, 32, 32),
        new THREE.MeshBasicMaterial({ color: 0xffff32 })
      );
      sphere3.position.x = 4;

      scene.add(sphere1, sphere2, sphere3);

      let meshs = [sphere1, sphere2, sphere3];
      const mouse = new THREE.Vector2();
      const raycaster = new THREE.Raycaster();
      window.addEventListener("mousedown", (event) => {
        //归一化处理
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
        //射线起点为相机的位置，终点为鼠标点击的位置
        raycaster.setFromCamera(mouse, camera);
        const intersects = raycaster.intersectObjects(meshs);
        for (const mesh of meshs) {
          mesh.material.color.set(new THREE.Color(0xffff33));
        }
        for (const intersectObject of intersects) {
          intersectObject.object.material.color.set(new THREE.Color(0xff0033));
        }
      });

      //控制插件
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true; //开启惯性,需要和update方法配合使用

      //动画函数
      function animate() {
        requestAnimationFrame(animate);
        controls.update();
        renderer.render(scene, camera);
      }
      animate();
    </script>
</body>

</html>